package jsyf.oa.service.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.contract.ContractMainDao;
import jsyf.oa.dao.device.DeviceDisplaceDao;
import jsyf.oa.dao.device.DeviceOutBoundDao;
import jsyf.oa.dao.device.DeviceTransportChangeDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.contract.ContractMainEntity;
import jsyf.oa.entity.device.*;
import jsyf.oa.entity.system.*;
import jsyf.oa.facade.device.DeviceDisplaceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by y on 2018/7/3.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DeviceDisplaceService implements DeviceDisplaceFacade {
    @Autowired
    private DeviceDisplaceDao deviceDisplaceDao;
    @Autowired
    private DeviceTransportChangeDao deviceTransportChangeDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private DeviceOutBoundDao deviceOutBoundDao;
    @Autowired
    private ContractMainDao contractMainDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private TokenDao tokenDao;
    @Override
    public JSONObject getDisplaceList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        /*旧机/旧车/旧房屋
        * type=1:旧机
        * type=2:旧车
        * type=3:房屋
        * */
        String type = jsonParams.getString("type");
        if (StringUtils.isNotBlank(type) && StringUtils.isNotEmpty(type)) {
            condition.append(" AND DEL_FLAG = 0 AND TYPE = " + type);
        }
        /*状态*/
        String state = jsonParams.getString("state");
        if (StringUtils.isNotBlank(state) && StringUtils.isNotEmpty(state)) {
            condition.append(" AND STATE = '" + state + "' ");
        }
        /*模糊查询*/
        String key = jsonParams.getString("key").trim();
        if (StringUtils.isNotBlank(key) && StringUtils.isNotEmpty(key)) {
            condition.append(" AND ( COMPANY_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR BRAND_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR MODEL_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR REPLACEMENT_TYPE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR STORE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR SEQUENCE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR STATE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOURS LIKE ? ");
            sqlArgs.add("%" + key + "%'");
            condition.append(" OR FACTORY_DATE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" )");
        }
        //必须成交成功的旧机才能带出来
        condition.append(" AND WHETHER_TO_CLOSE='1'\n");
        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId});
        String manageFlag = userList.get(0).getString("manageFlag");
        List<JSONObject> companyList = new ArrayList<JSONObject>();
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(manageFlag)) {
            if (!manageFlag.equals("1")) {
                companyList = companyDao.getJSONListByCondition(" and id in (SELECT \n" +
                        "v_sys_part_time_for_report.companyId\n" +
                        "FROM v_sys_part_time_for_report\n" +
                        "WHERE userId=?)\n" +
                        "and t_sys_company.del_flag=0 AND (t_sys_company.PARENT_ID='201712161613432EAF27DBCCB7D0E6CA')\n" +
                        "group by t_sys_company.id", new Object[]{userId});
            } else {
                companyList = companyDao.getJSONListByCondition(" and del_flag=0 and PARENT_ID='201712161613432EAF27DBCCB7D0E6CA' group by t_sys_company.id", new Object[]{});
            }
        }
        StringBuilder companyIds = new StringBuilder();
        String companyListIds = "";
        if (companyList.size() > 0) {
            for (JSONObject object : companyList) {
                companyIds.append("'");
                companyIds.append(object.getString("id"));
                companyIds.append("'");
                companyIds.append(",");
            }
            companyListIds = companyIds.toString().substring(0, companyIds.toString().length() - 1);
            condition.append(" and FK_COMPANY_ID in (" + companyListIds + ")");
        }
        condition.append("\n" +
                "AND AUDIT_FLAG!=-1\n" +
                "OR (CREATE_USER_ID='" + userId + "' AND TYPE=" + type + " \n");
        if (StringUtils.isNotBlank(state) && StringUtils.isNotEmpty(state)) {
            condition.append(" AND STATE = '" + state + "'");
        }
        condition.append(" )");
        condition.append(" OR (UPDATE_USER_ID='" + userId + "' AND TYPE=" + type + "\n");
        if (StringUtils.isNotBlank(state) && StringUtils.isNotEmpty(state)) {
            condition.append(" AND STATE = '" + state + "'");
        }
        condition.append(" AND AUDIT_FLAG !=- 1");
        condition.append(" )");
        condition.append(" OR (AUDIT_ID='" + userId + "' AND TYPE=" + type + "");
        if (StringUtils.isNotBlank(state) && StringUtils.isNotEmpty(state)) {
            condition.append(" AND STATE = '" + state + "'");
        }
        condition.append(" AND AUDIT_FLAG !=- 1");
        condition.append(" )");
        condition.append(" ORDER BY AUDIT_FLAG, CREATE_TIME DESC");
        //查询list
        List<JSONObject> records = deviceDisplaceDao.getJSONListByCondition(condition.toString(), sqlArgs.toArray());
        /*查询不同状态的数目*/
        JSONObject countList = deviceDisplaceDao.getAllCount(condition.toString(), sqlArgs.toArray());
        // 子数组对象
        JSONObject result = new JSONObject();
        result.put("records", records);
        result.put("countList", countList);
        return result;
    }

    /*旧机查询*/
    @Override
    public JSONObject getDisplaceListNew(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        /*旧机/旧车/旧房屋
        * type=1:旧机
        * type=2:旧车
        * type=3:房屋
        * */
        String type = jsonParams.getString("type");
        if (StringUtils.isNotBlank(type) && StringUtils.isNotEmpty(type)) {
            condition.append(" AND DEL_FLAG = 0 AND TYPE = " + type);
        }
        /*状态*/
        String state = jsonParams.getString("state");
        if (StringUtils.isNotBlank(state) && StringUtils.isNotEmpty(state)) {
            condition.append(" AND STATE = '" + state + "' ");
        }
        /*模糊查询*/
        String key = jsonParams.getString("key").trim();
        if (StringUtils.isNotBlank(key) && StringUtils.isNotEmpty(key)) {
            condition.append(" AND ( COMPANY_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR BRAND_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR MODEL_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR REPLACEMENT_TYPE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_NAME LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR STORE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR SEQUENCE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR STATE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOURS LIKE ? ");
            sqlArgs.add("%" + key + "%'");
            condition.append(" OR FACTORY_DATE LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" OR HOUSE_ADDRESS LIKE ? ");
            sqlArgs.add("%" + key + "%");
            condition.append(" )");
        }
        //必须成交成功的旧机才能带出来
        condition.append(" AND WHETHER_TO_CLOSE='1'\n");

        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId});
        String manageFlag = userList.get(0).getString("manageFlag");
        List<JSONObject> companyList = new ArrayList<JSONObject>();
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(manageFlag)) {
            if (!manageFlag.equals("1")) {
                companyList = companyDao.getJSONListByCondition(" and id in (SELECT \n" +
                        "v_sys_part_time_for_report.companyId\n" +
                        "FROM v_sys_part_time_for_report\n" +
                        "WHERE userId=?)\n" +
                        "and t_sys_company.del_flag=0 AND (t_sys_company.PARENT_ID='201712161613432EAF27DBCCB7D0E6CA')\n" +
                        "group by t_sys_company.id", new Object[]{userId});
            } else {
                companyList = companyDao.getJSONListByCondition(" and del_flag=0 and PARENT_ID='201712161613432EAF27DBCCB7D0E6CA' group by t_sys_company.id", new Object[]{});
            }
        }
        StringBuilder companyIds = new StringBuilder();
        String companyListIds = "";
        if (companyList.size() > 0) {
            for (JSONObject object : companyList) {
                companyIds.append("'");
                companyIds.append(object.getString("id"));
                companyIds.append("'");
                companyIds.append(",");
            }
            companyListIds = companyIds.toString().substring(0, companyIds.toString().length() - 1);
            condition.append(" and FK_COMPANY_ID in (" + companyListIds + ")");
        }
        /*保存草稿创建人等于userId才能带出草稿信息*/
       /* condition.append("AND (\n" +
                "AUDIT_FLAG<>-1\n" +
                "OR(AUDIT_FLAG=-1&&CREATE_USER_ID= '" + userId + "'))\n");*/
        /*排序*/
        condition.append(" ORDER BY AUDIT_FLAG,CREATE_TIME DESC");
        //查询list
        List<JSONObject> records = deviceDisplaceDao.getJSONListByCondition(condition.toString(), sqlArgs.toArray());
        /*查询不同状态的数目*/
        JSONObject countList = deviceDisplaceDao.getAllCount(condition.toString(), sqlArgs.toArray());
        // 子数组对象
        JSONObject result = new JSONObject();
        result.put("records", records);
        result.put("countList", countList);
        return result;
    }

    @Override
    public JSONObject getDisplaceById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        StringBuffer condition = new StringBuffer();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        JSONObject result = new JSONObject();
        String deviceSampleid = jsonParams.getString("id");
        JSONObject sampleObj = deviceDisplaceDao.getJSONById(deviceSampleid);
        System.out.println(between_days(sampleObj.getString("createTime").substring(0,10), sdf.format(new Date())));
        BigDecimal fundPossessionCost=new BigDecimal(between_days(sampleObj.getString("createTime").substring(0,10), sdf.format(new Date()))* 0.0007);
        sampleObj.put("fundPossessionCost",fundPossessionCost.multiply(sampleObj.getBigDecimal("estimatePrice")).setScale(2, BigDecimal.ROUND_HALF_UP));
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer.append("AND moduleId=" + " '" + deviceSampleid + " ' AND ATTACH_MODULE=3");
        List<JSONObject> attaches = deviceDisplaceDao.queryForJsonList(stringBuffer.toString(), new Object[]{});
        if (attaches.size() == 0) {
            attaches = new ArrayList<JSONObject>();
        }
        sampleObj.put("attaches", attaches);
        StringBuffer stringBuffer2 = new StringBuffer();
        stringBuffer2.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer2.append("AND moduleId=" + " '" + deviceSampleid + " ' AND ATTACH_MODULE=4");
        List<JSONObject> devicePictures = deviceDisplaceDao.queryForJsonList(stringBuffer2.toString(), new Object[]{});
        if (devicePictures.size() == 0) {
            devicePictures = new ArrayList<JSONObject>();
        }
        sampleObj.put("devicePictures", devicePictures);
        /*查询物流变更*/
        condition.append("AND DEVICE_ID=" + " '" + deviceSampleid + "'" + "\n");
        JSONObject changeObj = deviceTransportChangeDao.getChangeByDeviceId(condition.toString());
        /*查询出库信息*/
        List<JSONObject> outJsonList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =0 ORDER BY CREATE_TIME DESC", new Object[]{deviceSampleid});
        JSONObject outBoundRecord = new JSONObject();
        if (outJsonList.size() > 0) {
            outBoundRecord.put("flag", "1");
            outBoundRecord.put("main", outJsonList.get(0));
            JSONObject contract = contractMainDao.getJSONById(outJsonList.get(0).getString("contractId"));
            outBoundRecord.put("contract", contract);
        } else {
            outBoundRecord.put("flag", "0");
        }
        List<JSONObject> outCertificates = deviceDisplaceDao.getCertificatesByOutId(deviceOutBoundDao.getId(deviceSampleid, "0"));
        List<JSONObject> outDevicePictures = deviceDisplaceDao.getDevicePicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "0"));
        List<JSONObject> outDrayPictures = deviceDisplaceDao.getDrayPicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "0"));
        result.put("outBoundRecord", outBoundRecord);
        result.put("outCertificates", outCertificates);
        result.put("outDevicePictures", outDevicePictures);
        result.put("outDrayPictures", outDrayPictures);
        /*移库信息*/
        List<JSONObject> moveJsonList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =1 ORDER BY CREATE_TIME DESC", new Object[]{deviceSampleid});
        JSONObject moveBoundRecord = new JSONObject();
        if (moveJsonList.size() > 0) {
            moveBoundRecord.put("flag", "1");
            moveBoundRecord.put("main", moveJsonList.get(0));
        } else {
            moveBoundRecord.put("flag", "0");
        }
        List<JSONObject> moveCertificates = deviceDisplaceDao.getCertificatesByOutId(deviceOutBoundDao.getId(deviceSampleid, "1"));
        List<JSONObject> moveDevicePictures = deviceDisplaceDao.getDevicePicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "1"));
        List<JSONObject> moveDrayPictures = deviceDisplaceDao.getDrayPicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "1"));
        result.put("moveBoundRecord", moveBoundRecord);
        result.put("moveCertificates", moveCertificates);
        result.put("moveDevicePictures", moveDevicePictures);
        result.put("moveDrayPictures", moveDrayPictures);
        /*退货信息*/
        List<JSONObject> returnJsonList = deviceOutBoundDao.getJSONListByCondition("AND SAMPLE_ID=? AND TYPE =2 ORDER BY CREATE_TIME DESC", new Object[]{deviceSampleid});
        JSONObject returnBoundRecord = new JSONObject();
        if (returnJsonList.size() > 0) {
            returnBoundRecord.put("flag", "1");
            returnBoundRecord.put("main", returnJsonList.get(0));
        } else {
            returnBoundRecord.put("flag", "0");
        }
        List<JSONObject> returnCertificates = deviceDisplaceDao.getCertificatesByOutId(deviceOutBoundDao.getId(deviceSampleid, "2"));
        List<JSONObject> returnDevicePictures = deviceDisplaceDao.getDevicePicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "2"));
        List<JSONObject> returnDrayPictures = deviceDisplaceDao.getDrayPicturesByOutId(deviceOutBoundDao.getId(deviceSampleid, "2"));
        result.put("returnBoundRecord", returnBoundRecord);
        result.put("returnCertificates", returnCertificates);
        result.put("returnDevicePictures", returnDevicePictures);
        result.put("returnDrayPictures", returnDrayPictures);
        /*查询历史审核记录*/
        List<JSONObject> auditHistory = auditHistoryDao.getJSONListByCondition("AND MAIN_ID= '" + deviceSampleid + "'\n", new Object[]{});
        result.put("displace", sampleObj);
        result.put("changeTransport", changeObj);
        result.put("auditHistory", auditHistory);
        return result;
    }

    @Override
    public JSONObject save(String jsonObject) {
        DeviceDisplaceEntity deviceDisplaceEntity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceDisplaceEntity.class);
        Integer rows = 0;
        JSONObject obj = new JSONObject();
        if (deviceDisplaceEntity.getModelName() != null) {
            deviceDisplaceEntity.setModelName(deviceDisplaceEntity.getModelName().toUpperCase());
        }
        if (deviceDisplaceEntity.getReplacementType() != null) {
            deviceDisplaceEntity.setReplacementType(deviceDisplaceEntity.getReplacementType().toUpperCase());
        }
        if ("0".equals(deviceDisplaceEntity.getId()) || com.alibaba.dubbo.common.utils.StringUtils.isBlank(deviceDisplaceEntity.getId())) {
            rows = deviceDisplaceDao.add(deviceDisplaceEntity);
        } else {
            rows = deviceDisplaceDao.update(deviceDisplaceEntity);
        }
        String mainId = deviceDisplaceEntity.getId();
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = deviceDisplaceEntity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(3);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    /*旧机保存*/
    @Override
    public JSONObject saveOldSample(String jsonObject) {
        DeviceDisplaceEntity deviceDisplaceEntity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceDisplaceEntity.class);
        AuditEntity auditEntity = new AuditEntity();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        Integer rows = 0;
        JSONObject obj = new JSONObject();
        String title="";
        String url="";
        if (deviceDisplaceEntity.getModelName() != null) {
            deviceDisplaceEntity.setModelName(deviceDisplaceEntity.getModelName().toUpperCase());
        }
        if (deviceDisplaceEntity.getReplacementType() != null) {
            deviceDisplaceEntity.setReplacementType(deviceDisplaceEntity.getReplacementType().toUpperCase());
        }
        if ("0".equals(deviceDisplaceEntity.getId()) || com.alibaba.dubbo.common.utils.StringUtils.isBlank(deviceDisplaceEntity.getId())) {
            if (!deviceDisplaceEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828")) {
               /*查询直属领导人*/
                JSONObject parent = userDao.getFirstParent(deviceDisplaceEntity.getCreateUserId());
                String parentId = parent.getString("id");//审核人Id
                String parentName = parent.getString("name");//审核人姓名
                String parentRoleName = parent.getString("roleName");//审核人职位
                Integer auditFlag = deviceDisplaceEntity.getAuditFlag();//审核状态
                Integer auditSort = 0;
                // Date auditTime=deviceDisplaceDao.getCurrentTime();//审核时间,领导审核时的时间
                //String auditAdvise="";//审核原因
                String modelName = "oldSample";
            /*新增主表记录*/
                deviceDisplaceEntity.setAuditName(parentName);
                deviceDisplaceEntity.setAuditId(parentId);
                deviceDisplaceEntity.setAuditRoleName(parentRoleName);
                try {
                    rows = deviceDisplaceDao.add(deviceDisplaceEntity);
                }catch (Exception e){
                    obj.put("records", "保存失败");
                    return obj;
                }
        /*新增审核记录*/
                auditEntity.setMainId(deviceDisplaceEntity.getId());//旧设备表ID
                auditEntity.setAuditorId(parentId);//审核人Id
                auditEntity.setAuditorName(parentName);//审核人姓名
                auditEntity.setRoleName(parentRoleName);//审核人职位
                auditEntity.setAuditFlag(auditFlag);//审核状态
                auditEntity.setAuditSort(auditSort);
                auditEntity.setModuleName(modelName);
                Integer auditRow = auditDao.add(auditEntity);
                if(deviceDisplaceEntity.getAuditFlag()!=-1){
                //标记以前的审核人、申请人消息为已读
                messageReceiverRead(deviceDisplaceEntity.getId(), 0);
                messageReceiverRead(deviceDisplaceEntity.getId(), 2);
               //付款成功后给申请人发消息，保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(deviceDisplaceEntity.getCreateUserId());
                messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());

                if(deviceDisplaceEntity.getType()==1){
                   title="旧机入库";
                }else{
                    title="旧车入库";
                }
                    //企业号:给修改人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds",deviceDisplaceEntity.getAuditId());
                    msgObject.put("content", String.format(OLDDEVICE_STATE_AUDIT,
                            deviceDisplaceEntity.getAuditName(),
                            title,
                            deviceDisplaceEntity.getModelName(),
                            deviceDisplaceEntity.getSequence(),
                            deviceDisplaceEntity.getCreateUserName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                messageEntity.setContent(String.format(OLDDEVICE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceDisplaceEntity.getCreateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                messageEntity.setMessageType(0);
                messageEntity.setMainId(deviceDisplaceEntity.getId());
                messageEntity.setDelFlag(0);
                if(deviceDisplaceEntity.getType()==1){
                url="/page/device/sample/oldSampleDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                }else{
                    url="/page/device/sample/oldCarDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                }
                messageEntity.setOpenUrl(url);
                messageEntity.setOpenTitle(String.format(OLDDEVICE_AUDIT_STATE_MESSAGE, deviceDisplaceEntity.getCreateUserName(),title));
                messageDao.add(messageEntity);

                //保存消息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(deviceDisplaceEntity.getAuditId());
                messageReceiverEntity.setUserType(2);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);
                //发消息
                jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }
            } else {
                deviceDisplaceEntity.setAuditFlag(1);
                rows = deviceDisplaceDao.add(deviceDisplaceEntity);
            }
        } else {
            /*修改*/
            DeviceDisplaceEntity main = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(deviceDisplaceEntity.getId());

            if (!deviceDisplaceEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")) {
                //驳回后提交需审核
                if ((main.getAuditFlag() == 2||main.getAuditFlag() ==-1)&&deviceDisplaceEntity.getAuditFlag()==0) {
                    JSONObject audit = userDao.getFirstParent(deviceDisplaceEntity.getUpdateUserId());
                    //修改审核人信息
                    deviceDisplaceEntity.setAuditName(audit.getString("name"));
                    deviceDisplaceEntity.setAuditId(audit.getString("id"));
                    JSONObject user = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{audit.getString("id")}).get(0);
                    deviceDisplaceEntity.setAuditRoleName(user.getString("roleName"));
                    deviceDisplaceEntity.setAuditAdvise("");
                    deviceDisplaceEntity.setAuditTime(main.getAuditTime());//前台处理
                    //修改审核状态；
                    deviceDisplaceEntity.setAuditFlag(deviceDisplaceEntity.getAuditFlag());
                    //修改修改人
                    deviceDisplaceEntity.setUpdateUserId(deviceDisplaceEntity.getUpdateUserId());
                    deviceDisplaceEntity.setUpdateUserName(deviceDisplaceEntity.getUpdateUserName());
                    //保留创建人
                    deviceDisplaceEntity.setCreateUserId(main.getCreateUserId());
                    deviceDisplaceEntity.setCreateUserName(main.getCreateUserName());

                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(deviceDisplaceEntity.getId(), 0);
                    messageReceiverRead(deviceDisplaceEntity.getId(), 2);
//付款成功后给申请人发消息，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(deviceDisplaceEntity.getUpdateUserId());
                    messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());

                    if(deviceDisplaceEntity.getType()==1){
                        title="旧机入库";
                    }else{
                        title="旧车入库";
                    }
                    //企业号:给修改人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds",deviceDisplaceEntity.getAuditId());
                    msgObject.put("content", String.format(OLDDEVICE_STATE_AUDIT,
                            deviceDisplaceEntity.getAuditName(),
                            title,
                            deviceDisplaceEntity.getModelName(),
                            deviceDisplaceEntity.getSequence(),
                            deviceDisplaceEntity.getUpdateUserName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    messageEntity.setContent(String.format(OLDDEVICE_STATE_AUDIT,
                            deviceDisplaceEntity.getAuditName(),
                            title,
                            deviceDisplaceEntity.getModelName(),
                            deviceDisplaceEntity.getSequence(),
                            deviceDisplaceEntity.getCreateUserName(),
                            DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(deviceDisplaceEntity.getId());
                    messageEntity.setDelFlag(0);
                    if(deviceDisplaceEntity.getType()==1){
                        url="/page/device/sample/oldSampleDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                    }else{
                        url="/page/device/sample/oldCarDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                    }
                    messageEntity.setOpenUrl(url);
                    messageEntity.setOpenTitle(String.format(OLDDEVICE_AUDIT_STATE_MESSAGE, deviceDisplaceEntity.getCreateUserName(),title));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(deviceDisplaceEntity.getAuditId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);
                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }else{
                    //如果正常修改，不审核
                    if(deviceDisplaceEntity.getAuditFlag()==0){
                        deviceDisplaceEntity.setAuditFlag(1);
                        deviceDisplaceEntity.setAuditTime(main.getAuditTime());
                        deviceDisplaceEntity.setCreateUserId(main.getCreateUserId());
                        deviceDisplaceEntity.setCreateUserName(main.getCreateUserName());
                    }else{//草稿
                        deviceDisplaceEntity.setAuditId("");
                        deviceDisplaceEntity.setAuditName("");
                        deviceDisplaceEntity.setAuditTime(null);
                        deviceDisplaceEntity.setCreateUserId(main.getCreateUserId());
                        deviceDisplaceEntity.setCreateUserName(main.getCreateUserName());
                    }

                }
            } else {
                deviceDisplaceEntity.setAuditTime(main.getAuditTime());
                deviceDisplaceEntity.setAuditFlag(1);
            }
            try{
            rows = deviceDisplaceDao.update(deviceDisplaceEntity);
            }catch (Exception e){
                obj.put("records", "保存失败");
                return obj;
            }
        }
        String mainId = deviceDisplaceEntity.getId();
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = deviceDisplaceEntity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(3);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        List<AttachmentEntity> devicePictures = deviceDisplaceEntity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(4);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        if (rows > 0) {
            obj.put("records", "保存成功");
            obj.put("message", jsonObjectList);
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    @Override
    public JSONObject saveHouse(String jsonObject) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonObject, JSONObject.class);
        DeviceDisplaceEntity deviceDisplaceEntity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceDisplaceEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        Integer rows = 0;
        String  title="旧房入库";
        String url="";
        JSONObject obj = new JSONObject();
        if (deviceDisplaceEntity.getModelName() != null) {
            deviceDisplaceEntity.setModelName(deviceDisplaceEntity.getModelName().toUpperCase());
        }
        if (deviceDisplaceEntity.getReplacementType() != null) {
            deviceDisplaceEntity.setReplacementType(deviceDisplaceEntity.getReplacementType().toUpperCase());
        }
        //主表添加审核信息
        //首先获取上级为第一审核人
        JSONObject audit=new JSONObject();
        if (deviceDisplaceEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")) {
            audit=userDao.getViewJSONById(deviceDisplaceEntity.getUpdateUserId());
        }else{
            audit = userDao.getFirstParent(deviceDisplaceEntity.getUpdateUserId());
        }
        //设置审核人
            deviceDisplaceEntity.setAuditName(audit.getString("name"));
            deviceDisplaceEntity.setAuditId(audit.getString("id"));
            deviceDisplaceEntity.setAuditRoleName(audit.getString("roleName"));
            deviceDisplaceEntity.setAuditTime(deviceDisplaceDao.getCurrentTime());
            deviceDisplaceEntity.setAuditAdvise("");
        //设置审核状态；
        deviceDisplaceEntity.setAuditFlag(deviceDisplaceEntity.getAuditFlag());
        if ("0".equals(deviceDisplaceEntity.getId()) || StringUtils.isBlank(deviceDisplaceEntity.getId())) {
            //设置创建人
            deviceDisplaceEntity.setCreateUserId(deviceDisplaceEntity.getCreateUserId());
            deviceDisplaceEntity.setCreateUserName(deviceDisplaceEntity.getCreateUserName());
            //设置修改人
            deviceDisplaceEntity.setUpdateUserId(deviceDisplaceEntity.getCreateUserId());
            deviceDisplaceEntity.setUpdateUserName(deviceDisplaceEntity.getCreateUserName());
            rows = deviceDisplaceDao.add(deviceDisplaceEntity);
            if (!deviceDisplaceEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828")&&deviceDisplaceEntity.getAuditFlag()!=-1) {
//企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds",deviceDisplaceEntity.getAuditId());
                msgObject.put("content", String.format(HOUSE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getCreateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(deviceDisplaceEntity.getId(), 0);
                    messageReceiverRead(deviceDisplaceEntity.getId(), 2);
                    //付款成功后给申请人发消息，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(deviceDisplaceEntity.getCreateUserId());
                    messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());
                    messageEntity.setContent(String.format(HOUSE_STATE_AUDIT,
                            deviceDisplaceEntity.getAuditName(),
                            title,
                            deviceDisplaceEntity.getHouseName(),
                            deviceDisplaceEntity.getHouseAddress(),
                            deviceDisplaceEntity.getCreateUserName(),
                            DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(deviceDisplaceEntity.getId());
                    messageEntity.setDelFlag(0);
                    url="/page/device/sample/houseDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                    messageEntity.setOpenUrl(url);
                    messageEntity.setOpenTitle(String.format(OLDDEVICE_AUDIT_STATE_MESSAGE, deviceDisplaceEntity.getCreateUserName(),title));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(deviceDisplaceEntity.getAuditId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);
                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
            }

        } else {
            DeviceDisplaceEntity oldDeviceDisplaceEntity = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(deviceDisplaceEntity.getId());
            //设置修改人
            deviceDisplaceEntity.setUpdateUserId(deviceDisplaceEntity.getCreateUserId());
            deviceDisplaceEntity.setUpdateUserName(deviceDisplaceEntity.getCreateUserName());
            //设置创建人
            deviceDisplaceEntity.setCreateUserId(oldDeviceDisplaceEntity.getCreateUserId());
            deviceDisplaceEntity.setCreateUserName(oldDeviceDisplaceEntity.getCreateUserName());
            if((oldDeviceDisplaceEntity.getAuditFlag() == 2||oldDeviceDisplaceEntity.getAuditFlag() ==-1)&&deviceDisplaceEntity.getAuditFlag()==0){

                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds",deviceDisplaceEntity.getAuditId());
                msgObject.put("content", String.format(HOUSE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getUpdateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                //标记以前的审核人、申请人消息为已读
                messageReceiverRead(deviceDisplaceEntity.getId(), 0);
                messageReceiverRead(deviceDisplaceEntity.getId(), 2);
                //付款成功后给申请人发消息，保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(deviceDisplaceEntity.getUpdateUserId());
                messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());
                messageEntity.setContent(String.format(HOUSE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getCreateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                messageEntity.setMessageType(0);
                messageEntity.setMainId(deviceDisplaceEntity.getId());
                messageEntity.setDelFlag(0);
                url="/page/device/sample/houseDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                messageEntity.setOpenUrl(url);
                messageEntity.setOpenTitle(String.format(OLDDEVICE_AUDIT_STATE_MESSAGE, deviceDisplaceEntity.getUpdateUserName(),title));
                messageDao.add(messageEntity);

                //保存消息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(deviceDisplaceEntity.getAuditId());
                messageReceiverEntity.setUserType(2);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);
                //发消息
                jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
            }
            Date createTime = deviceDisplaceDao.getJSONById(deviceDisplaceEntity.getId()).getDate("createTime");
            deviceDisplaceEntity.setCreateTime(createTime);
            rows = deviceDisplaceDao.update(deviceDisplaceEntity);
        }
        auditDao.removeByCondition("AND MAIN_ID = ? ", new String[]{deviceDisplaceEntity.getId()});
        //审核表添加审核信息
        AuditEntity auditEntity = new AuditEntity();
        int type = deviceDisplaceEntity.getType();
        if (type == 3) {
            auditEntity.setModuleName("oldHouse");
            //旧房屋是10
            this.saveAttachs(deviceDisplaceEntity, jsonPalams, "10");
        } else if (type == 2) {
            auditEntity.setModuleName("oldCar");
            //旧车是11
            this.saveAttachs(deviceDisplaceEntity, jsonPalams, "11");
        }
        auditEntity.setMainId(deviceDisplaceEntity.getId());
        auditEntity.setAuditFlag(0);
        auditEntity.setAuditAdvise("");
        auditEntity.setAuditorId(audit.getString("id"));
        auditEntity.setAuditorName(audit.getString("name"));
        auditEntity.setRoleName(audit.getString("roleName"));
        auditEntity.setAuditSort(0);
        auditEntity.setAuditTime(auditDao.getCurrentTime());
        auditDao.add(auditEntity);
        if (rows > 0) {
            obj.put("records", "保存成功");
            obj.put("message", jsonObjectList);
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String mainId = jsonPalams.getString("id");//获取主表Id
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String advise = jsonPalams.getString("advise");//意见
        String type = jsonPalams.getString("type");//类型
        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息

        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        DeviceDisplaceEntity deviceDisplaceEntity = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(mainId);
        deviceDisplaceEntity.setAuditFlag(Integer.parseInt(auditFlag));
        deviceDisplaceEntity.setAuditTime(deviceDisplaceDao.getCurrentTime());
        deviceDisplaceEntity.setAuditAdvise(advise);
        deviceDisplaceDao.update(deviceDisplaceEntity);
        //修改审核表信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回

        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(mainId);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userEntity.getName());
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
         String title="";
        String url="";
        if (type.equals("1")) {
            auditHistoryEntity.setAuditType(8);//旧机
            if("提车在途".equals(deviceDisplaceEntity.getState())||"库存".equals(deviceDisplaceEntity.getState())){
                title="旧机入库申请";
            }else{
                title="旧机交付申请";
            }
        }
        if (type.equals("2")) {
            auditHistoryEntity.setAuditType(6);//旧汽车
            if("提车在途".equals(deviceDisplaceEntity.getState())||"库存".equals(deviceDisplaceEntity.getState())){
                title="旧车入库申请";
            }else{
                title="旧车交付申请";
            }
        }
        if (type.equals("3")) {
            auditHistoryEntity.setAuditType(7);//旧房屋
            title="旧房入库申请";
        }
        auditHistoryDao.add(auditHistoryEntity);

        AuditEntity auditEntity = (AuditEntity) auditDao.getIBaseEntityByCondition(" AND MAIN_ID=?", new Object[]{mainId}).get(0);
        auditEntity.setAuditAdvise(advise);
        auditEntity.setAuditTime(auditDao.getCurrentTime());
        auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
        auditDao.update(auditEntity);
//驳回提醒
        if(deviceDisplaceEntity.getAuditFlag()==2){
//标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainId, 0);
            messageReceiverRead(mainId, 2);
            //付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceDisplaceEntity.getAuditId());
            messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());
            if(deviceDisplaceEntity.getType()!=3) {
                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", deviceDisplaceEntity.getUpdateUserId());
                msgObject.put("content", String.format(DEVICE_APPLICATION_REJECT,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceDisplaceEntity.getAuditAdvise(),
                        userEntity.getName(),
                        DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                messageEntity.setContent(String.format(DEVICE_APPLICATION_REJECT,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceDisplaceEntity.getAuditAdvise(),
                        userEntity.getName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            }else{
                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", deviceDisplaceEntity.getUpdateUserId());
                msgObject.put("content", String.format(HOUSE_APPLICATION_REJECT,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getAuditAdvise(),
                        userEntity.getName(),
                        DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                messageEntity.setContent(String.format(HOUSE_APPLICATION_REJECT,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getAuditAdvise(),
                        userEntity.getName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            }
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceDisplaceEntity.getId());
            messageEntity.setDelFlag(0);
            if(deviceDisplaceEntity.getType()==1){
                url="/page/device/sample/oldSampleDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }else if(deviceDisplaceEntity.getType()==2){
                url="/page/device/sample/oldCarDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }else{
                url="/page/device/sample/houseDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }
            messageEntity.setOpenUrl(url);
            messageEntity.setOpenTitle(String.format(DEVICE_APPLICATION_REJECT_MESSAGE, title,userEntity.getName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(deviceDisplaceEntity.getUpdateUserId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }else{
            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainId, 0);
            messageReceiverRead(mainId, 2);
            //付款成功后给申请人发消息，保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(deviceDisplaceEntity.getAuditId());
            messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());
            if(deviceDisplaceEntity.getType()!=3) {
                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", deviceDisplaceEntity.getUpdateUserId());
                msgObject.put("content", String.format(DEVICE_AUDIT_PASS,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceDisplaceEntity.getAuditName(),
                        DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                messageEntity.setContent(String.format(DEVICE_AUDIT_PASS,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceDisplaceEntity.getAuditName(),
                        userEntity.getName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            }else{
                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", deviceDisplaceEntity.getUpdateUserId());
                msgObject.put("content", String.format(HOUSE_AUDIT_PASS,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getAuditName(),
                        DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                messageEntity.setContent(String.format(HOUSE_AUDIT_PASS,
                        deviceDisplaceEntity.getUpdateUserName(),
                        title,
                        deviceDisplaceEntity.getHouseName(),
                        deviceDisplaceEntity.getHouseAddress(),
                        deviceDisplaceEntity.getAuditName(),
                        userEntity.getName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            }
            messageEntity.setMessageType(0);
            messageEntity.setMainId(deviceDisplaceEntity.getId());
            messageEntity.setDelFlag(0);
            if(deviceDisplaceEntity.getType()==1){
                url="/page/device/sample/oldSampleDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }else if(deviceDisplaceEntity.getType()==2){
                url="/page/device/sample/oldCarDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }else{
                url="/page/device/sample/houseDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
            }
            messageEntity.setOpenUrl(url);
            messageEntity.setOpenTitle(String.format(DEVICE_APPLICATION_PASS_MESSAGE,title,userEntity.getName()));
            messageDao.add(messageEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(deviceDisplaceEntity.getUpdateUserId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }

        JSONObject object=new JSONObject();
        object.put("flag",true);
        object.put("message", jsonObjectList);
        return object;
    }
    /*
    * 保存对应的附件
    * */
    public void saveAttachs(DeviceDisplaceEntity deviceDisplaceEntity, JSONObject jsonPalams, String module) {
        //删除现有的附件模块表中的信息
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=? ", new String[]{deviceDisplaceEntity.getId(), module});
        //获取上传附件的信息
        List<JSONObject> attachModuleList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches"), JSONObject.class);
        if (!StringUtils.isBlank(deviceDisplaceEntity.getId()) && attachModuleList.size() > 0) {
            for (JSONObject attachModule : attachModuleList) {
                //附件信息写入附件-模板表中
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(Integer.parseInt(module));
                attachModuleEntity.setModuleId(deviceDisplaceEntity.getId());
                attachModuleDao.add(attachModuleEntity);
            }
        }
    }
    @Override
    public JSONObject saveTransport(String jsonObject) {
        DeviceTransportEntity deviceTransportEntity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceTransportEntity.class);
        Integer rows = 0;
        JSONObject obj = new JSONObject();

        if (deviceTransportEntity.getModelCarLicense() != null) {
            deviceTransportEntity.setModelCarLicense(deviceTransportEntity.getModelCarLicense().toUpperCase());
        }
        if ("0".equals(deviceTransportEntity.getId()) || com.alibaba.dubbo.common.utils.StringUtils.isBlank(deviceTransportEntity.getId())) {
            rows = deviceDisplaceDao.add(deviceTransportEntity);
        } else {
            rows = deviceDisplaceDao.update(deviceTransportEntity);
        }
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    @Override
    public JSONObject saveChange(String jsonObject) {
        DeviceTransportChangeEntity deviceTransportChangeEntity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceTransportChangeEntity.class);
        Integer rows = 0;
        JSONObject obj = new JSONObject();
        if (deviceTransportChangeEntity.getModelCarLicense() != null) {
            deviceTransportChangeEntity.setModelCarLicense(deviceTransportChangeEntity.getModelCarLicense().toUpperCase());
        }
        if ("0".equals(deviceTransportChangeEntity.getId()) || com.alibaba.dubbo.common.utils.StringUtils.isBlank(deviceTransportChangeEntity.getId())) {
            rows = deviceTransportChangeDao.add(deviceTransportChangeEntity);
        } else {
            rows = deviceTransportChangeDao.update(deviceTransportChangeEntity);
        }
        if (rows > 0) {
            obj.put("records", "保存成功");
        } else {
            obj.put("records", "保存失败");
        }
        return obj;
    }

    @Override
    public JSONObject delById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        Integer row = deviceDisplaceDao.delById(id);
        JSONObject obj = new JSONObject();
        if (row > 0) {
            obj.put("records", "删除成功");
        } else {
            obj.put("records", "删除失败");
        }
        return obj;
    }

    @Override
    public JSONObject removeById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        Integer row = deviceDisplaceDao.removeById(id);
        /*删除审核表记录*/
        Integer rowAudit = auditDao.removeByCondition("AND MAIN_ID=?", new String[]{id});

        JSONObject obj = new JSONObject();
        if (row > 0) {
            obj.put("records", "删除成功");
        } else {
            obj.put("records", "删除失败");
        }
        return obj;
    }
    /*出库*/
    @Override
    public JSONObject outBound(String jsonObject) {
        DeviceOutBoundEntity entity = JSON.toJavaObject(JSON.parseObject(jsonObject), DeviceOutBoundEntity.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DeviceOutBoundMainEntity deviceOutBoundMainEntity = entity.getMain();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String title="";
        String url="";
        int type = deviceOutBoundMainEntity.getType();

        if (deviceOutBoundMainEntity.getId().equals("0") || StringUtils.isBlank(deviceOutBoundMainEntity.getId())) {

            deviceOutBoundDao.add(deviceOutBoundMainEntity);
            DeviceDisplaceEntity deviceDisplaceEntity = (DeviceDisplaceEntity) deviceDisplaceDao.getIBaseEntityById(deviceOutBoundMainEntity.getSampleId());
            /*移库退货无合同号*/
            if (!StringUtils.isBlank(deviceOutBoundMainEntity.getContractId())) {
                ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(deviceOutBoundMainEntity.getContractId());
                if (!StringUtils.isBlank(deviceDisplaceEntity.getSequence())) {
                    contractMainEntity.setSerialNo(deviceDisplaceEntity.getSequence());
                }
                contractMainEntity.setHaveDelivery(1);

                contractMainEntity.setDeliveryDate(sdf.format(new Date()));

                if (!StringUtils.isBlank(deviceOutBoundMainEntity.getDelivery_address())) {
                    contractMainEntity.setDeliveryAddress(deviceOutBoundMainEntity.getDelivery_address());
                }
                contractMainDao.update(contractMainEntity);
            }
            /*修改主表当前审核信息*/
            //设置修改人
            deviceDisplaceEntity.setUpdateUserId(deviceOutBoundMainEntity.getCreateUserId());
            deviceDisplaceEntity.setUpdateUserName(deviceOutBoundMainEntity.getCreateUserName());
            if (!deviceDisplaceEntity.getUpdateUserId().equals("201711271733404C9DA1461F2421F828")&&deviceOutBoundMainEntity.getType()==0) {
                deviceDisplaceEntity.setAuditFlag(0);
                deviceDisplaceEntity.setAuditAdvise("");
                deviceDisplaceEntity.setAuditTime(null);
               if(deviceDisplaceEntity.getType()==1){
                   title="旧机交付";
               }else{
                   title="旧车交付";
               }
                //企业号:给修改人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds",deviceDisplaceEntity.getAuditId());
                msgObject.put("content", String.format(OLDDEVICE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceOutBoundMainEntity.getCreateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

//标记以前的审核人、申请人消息为已读
                messageReceiverRead(deviceDisplaceEntity.getId(), 0);
                messageReceiverRead(deviceDisplaceEntity.getId(), 2);
//付款成功后给申请人发消息，保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(deviceOutBoundMainEntity.getCreateUserId());
                messageEntity.setCreateTime(deviceDisplaceDao.getCurrentTime());
                messageEntity.setContent(String.format(OLDDEVICE_STATE_AUDIT,
                        deviceDisplaceEntity.getAuditName(),
                        title,
                        deviceDisplaceEntity.getModelName(),
                        deviceDisplaceEntity.getSequence(),
                        deviceOutBoundMainEntity.getCreateUserName(),
                        DateUtils.parse(deviceDisplaceDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                messageEntity.setMessageType(0);
                messageEntity.setMainId(deviceDisplaceEntity.getId());
                messageEntity.setDelFlag(0);
                if(deviceDisplaceEntity.getType()==1){
                    url="/page/device/sample/oldSampleDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                }else{
                    url="/page/device/sample/oldCarDetail.html?pageType=audit&&id=" + deviceDisplaceEntity.getId() +"&&isAdd=0"+"&openType=dialog";
                }
                messageEntity.setOpenUrl(url);
                messageEntity.setOpenTitle(String.format(OLDDEVICE_AUDIT_STATE_MESSAGE, deviceOutBoundMainEntity.getCreateUserName(),title));
                messageDao.add(messageEntity);

                //保存消息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(deviceDisplaceEntity.getAuditId());
                messageReceiverEntity.setUserType(2);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);
                //发消息
                jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
            } else {
                deviceDisplaceEntity.setAuditFlag(1);
            }

            /*出库、移库、退货后库存地都为空*/
            deviceDisplaceEntity.setStoreAddress("");
           /*根据出库类型设置状态*/
            if (type == 0) {
                deviceDisplaceEntity.setState("交付在途");
            } else if (type == 1) {
                deviceDisplaceEntity.setState("移库在途");
            } else {
                deviceDisplaceEntity.setState("退货在途");
            }
            deviceDisplaceDao.update(deviceDisplaceEntity);
        } else {
            deviceOutBoundDao.update(deviceOutBoundMainEntity);
        }

        /*出库表ID*/
        String mainId = deviceOutBoundMainEntity.getId();
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
         /*获取司机证件附件 6*/
        List<AttachmentEntity> certificateList = entity.getCertificates();
        if (certificateList != null && certificateList.size() > 0) {
            for (AttachmentEntity attach : certificateList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(6);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取设备照片附件 7*/
        List<AttachmentEntity> devicePictures = entity.getDevicePictures();
        if (devicePictures != null && devicePictures.size() > 0) {
            for (AttachmentEntity attach : devicePictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(7);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        /*获取板车照片附件 8*/
        List<AttachmentEntity> drayPictures = entity.getDrayPictures();
        if (drayPictures != null && drayPictures.size() > 0) {
            for (AttachmentEntity attach : drayPictures) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(8);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        JSONObject obj = new JSONObject();
        obj.put("id", deviceOutBoundMainEntity.getId());
        obj.put("message", jsonObjectList);
        return obj;
    }

    @Override
    public JSONObject findCompanyList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        StringBuffer contion = new StringBuffer();
        String companyId = jsonParams.getString("companyId");
        if (!StringUtils.isBlank(companyId)) {
            contion.append(" AND ID=" + " '" + companyId + "'\n");
        } else {
            contion.append("AND PARENT_ID='201712161613432EAF27DBCCB7D0E6CA'\n" +
                    "AND DEL_FLAG<>1\n" +
                    "ORDER BY SORT_NO");
        }
        List<JSONObject> records = deviceDisplaceDao.findCompanyList(contion.toString());
        JSONObject result = new JSONObject();
        if (records != null) {
            result.put("records", records);
        } else {
            result.put("records", "null");
        }
        return result;
    }

    @Override
    public JSONObject findRegionByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        StringBuffer contion = new StringBuffer();
        contion.append("AND COMPANY_ID= '" + companyId + "'\n");
        contion.append("AND PARENT_ID=0\n" +
                "AND DEL_FLAG<>1\n" +
                "ORDER BY\n" +
                "SORT_NO");
        List<JSONObject> regions = deviceDisplaceDao.findRegionByCompanyId(contion.toString());
        JSONObject result = new JSONObject();
        if (regions != null) {
            result.put("regions", regions);
        } else {
            result.put("regions", "null");
        }
        return result;
    }

    @Override
    public JSONObject findBigRegionManagerByRegionId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String regionId = jsonParams.getString("regionId");
        StringBuffer contion = new StringBuffer();
        contion.append("AND t_sys_user_2_region.REGION_ID='" + regionId + "'\n");
        contion.append("AND v_sys_user.roleName='大区经理'\n" +
                "AND v_sys_user.delFlag<>1\n");
        List<JSONObject> regions = deviceDisplaceDao.findBigRegionManagerByRegionId(contion.toString());
        JSONObject result = new JSONObject();
        if (regions != null) {
            result.put("regions", regions);
        } else {
            result.put("regions", "null");
        }
        return result;
    }

    @Override
    public JSONObject findRegionManagerByBigRegionManagerId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String bigRegionId = jsonParams.getString("bigRegionId");
        StringBuffer contion = new StringBuffer();
        contion.append("AND t_sys_region.ID='" + bigRegionId + "'\n");
        List<JSONObject> regions = deviceDisplaceDao.findRegionManagerByBigRegionManagerId(contion.toString());
        JSONObject result = new JSONObject();
        if (regions != null) {
            result.put("regions", regions);
        } else {
            result.put("regions", "null");
        }
        return result;
    }

    @Override
    public List<JSONObject> getExportList(String jsonData) {

        return deviceDisplaceDao.getExportList(jsonData);
    }

    @Override
    public JSONObject getBigManagerAndRegion(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        JSONObject json=deviceDisplaceDao.getBigManagerAndRegion(userId);
        return json;
    }

    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }
    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }
    public static int between_days(String a, String b) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定义时间格式

        Calendar calendar_a = Calendar.getInstance();// 获取日历对象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串转Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 设置日历
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化异常
        }

        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();

        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//计算相差天数
        return Integer.parseInt(String.valueOf(between_days));
    }
}